<?php
/**
 * User: hjd-yao
 * Date: 2019/5/9
 * Time: 12:24
 */

namespace App\Helpers\Uploader;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use OSS\Core\OssException;
use OSS\OssClient;

class UploadAliyun extends UploadImage
{
    private $group;

    public function __construct(array $config, Request $request)
    {
        parent::__construct($config, $request);
    }

    public function doUpload()
    {
        $file = $this->request->file($this->fileField);
        if (empty($file)) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return false;
        }
        if (!$file->isValid()) {
            $this->stateInfo = $this->getStateInfo($file->getError());
            return false;
        }

        $this->file = $file;
        $this->group = $this->config["imageGroup"]??'img';

        $this->oriName = $this->file->getClientOriginalName();

        $this->fileSize = $this->file->getSize();

        $this->fileType = $this->getFileExt();


        $this->fileMd5 = md5_file($this->file->getPathname());

        $this->fileSha1 = sha1_file($this->file->getPathname());

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return false;
        }
        //检查是否不允许的文件格式
        if (!$this->checkType()) {
            $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            return false;
        }

        if(!$this->checkMime()){
            $this->stateInfo = $this->getStateInfo('ERROR_MIME_TYPE');
            return false;
        }

        if(!$this->checkHex()){
            $this->stateInfo = $this->getStateInfo('IMG_IS_DANGER');
            return false;
        }

        $disk = Storage::disk('oss');
        $path = $disk->put($this->group,$this->file);

        if($path){
            $url = $disk->url($path);
            $this->fullName = $this->fileId = $url;
            $this->stateInfo = $this->stateMap[0];
        }else{
            $this->stateInfo = $this->getStateInfo('ERROR_WRITE_CONTENT');
        }
    }

    public function getFileInfo()
    {
        if($this->stateInfo == 'SUCCESS'||$this->stateInfo == 'IMG_EXIST'){
            return [
                'status'=>1,
                'state'=>$this->stateInfo,
                "msg" => $this->stateInfo,
                "url" => $this->fullName,
                "id" => $this->fileId,
            ];
        }else{
            return [
                'status'=>0,
                'state'=>$this->stateInfo,
                "msg" => $this->stateInfo,
            ];
        }
    }

    public function uploadBase64(Request $request)
    {
        $field = $request->post('imgField');
        $imgBase64 = $request->post($field);
        $group = $request->post('group');

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgBase64, $res)) {
            //获取图片类型
            //获取图片类型
            $type = $res[2];
            if(!in_array('.'.$type, $this->config["allowFiles"])){
                return [
                    'status'=>0,
                    "msg" =>'上传图片格式不正确'
                ];
            }
            //图片名字
            $fileName = md5(time()) . '.' . $type;


            //dd($res,$imgBase64);

            // 临时文件
            $tmpfname = tempnam(sys_get_temp_dir(), "FOO");
            //dd($tmpfname);

            //保存图片
            $handle = fopen($tmpfname, "w");
            //阿里云oss上传的文件目录
            $dst = $group.'/'.$fileName;
            if (fwrite($handle, base64_decode(str_replace($res[1], '', $imgBase64))))
            {
                $accessKeyId =config('filesystems.disks.oss.access_key');
                $accessKeySecret = config('filesystems.disks.oss.secret_key');
                $endpoint = config('filesystems.disks.oss.endpoint');
                $bucket= config('filesystems.disks.oss.bucket');

                try{
                    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                    $res = $ossClient->uploadFile($bucket, $dst, $tmpfname);
                    fclose($handle);
                    #删除本地该图片
                    unlink($tmpfname);

                    return [
                        'status'=>1,
                        "url" => $res['oss-request-url']
                    ];
                }catch(OssException $e) {
                    return [
                        'status'=>0,
                        "msg" => $e->getMessage()
                    ];
                }

            }
            return [
                'status'=>0,
                "msg" => '图标写入失败'
            ];
        }
        return [
            'status'=>0,
            "msg" =>'图片信息不完整'
        ];
    }
}